<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>泰联读书打卡小程序</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Microsoft YaHei', Arial, sans-serif;
      background-color: #f5f5f5;
      color: #333;
      line-height: 1.6;
    }

    /* 自定义弹出层样式 */
    .custom-modal {
      display: none;
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      animation: fadeIn 0.3s ease;
    }

    .custom-modal-content {
      background-color: #fff;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 0;
      border-radius: 8px;
      width: 90%;
      max-width: 400px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
      animation: slideIn 0.3s ease;
    }

    .custom-modal-header {
      padding: 20px;
      background-color: #3498db;
      color: white;
      border-radius: 8px 8px 0 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .custom-modal-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }

    .custom-modal-close {
      color: white;
      font-size: 24px;
      font-weight: bold;
      cursor: pointer;
      line-height: 1;
    }

    .custom-modal-body {
      padding: 20px;
      text-align: center;
    }

    .custom-modal-message {
      margin: 0 0 20px 0;
      font-size: 16px;
      color: #333;
    }

    .custom-modal-footer {
      padding: 15px 20px;
      text-align: center;
      border-top: 1px solid #eee;
    }

    .custom-modal-button {
      background-color: #3498db;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 16px;
      transition: background-color 0.3s;
    }

    .custom-modal-button:hover {
      background-color: #2980b9;
    }

    .custom-modal-button.success {
      background-color: #27ae60;
    }

    .custom-modal-button.success:hover {
      background-color: #219653;
    }

    .custom-modal-button.error {
      background-color: #e74c3c;
    }

    .custom-modal-button.error:hover {
      background-color: #c0392b;
    }

    .custom-modal-button.primary {
      background-color: #3498db;
      color: white;
      font-weight: bold;
    }

    .custom-modal-button.primary:hover {
      background-color: #2980b9;
    }

    @keyframes fadeIn {
      from {
        opacity: 0;
      }

      to {
        opacity: 1;
      }
    }

    @keyframes slideIn {
      from {
        transform: translate(-50%, -60%);
        opacity: 0;
      }

      to {
        transform: translate(-50%, -50%);
        opacity: 1;
      }
    }

    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
    }

    header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 20px;
      border-radius: 10px;
      margin-bottom: 20px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    h1 {
      text-align: center;
      font-size: 2em;
      margin-bottom: 10px;
    }

    .notification {
      background-color: #fff3cd;
      border: 1px solid #ffeaa7;
      color: #856404;
      padding: 15px;
      border-radius: 5px;
      margin-bottom: 20px;
      overflow: hidden;
      white-space: nowrap;
      position: relative;
    }

    .notification-content {
      display: inline-block;
      padding-left: 100%;
      animation: scroll-left 20s linear infinite;
    }

    @keyframes scroll-left {
      0% {
        transform: translateX(0);
      }

      100% {
        transform: translateX(-100%);
      }
    }

    .card {
      background: white;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      padding: 25px;
      margin-bottom: 30px;
    }

    .card-title {
      font-size: 1.5em;
      color: #333;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 2px solid #667eea;
    }

    .form-group {
      margin-bottom: 20px;
    }

    label {
      display: block;
      margin-bottom: 8px;
      font-weight: bold;
      color: #555;
    }

    input,
    textarea,
    select {
      width: 100%;
      padding: 12px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 16px;
      transition: border-color 0.3s;
    }

    input:focus,
    textarea:focus,
    select:focus {
      outline: none;
      border-color: #667eea;
      box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
    }

    textarea {
      min-height: 120px;
      resize: vertical;
    }

    .btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 12px 30px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
      font-weight: bold;
      transition: transform 0.2s, box-shadow 0.2s;
    }

    .btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .btn:active {
      transform: translateY(0);
    }

    .progress-container {
      margin: 20px 0;
    }

    .progress-bar {
      height: 20px;
      background-color: #e0e0e0;
      border-radius: 10px;
      overflow: hidden;
      margin-bottom: 10px;
    }

    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #4CAF50, #8BC34A);
      border-radius: 10px;
      transition: width 0.5s ease;
    }

    .progress-text {
      text-align: center;
      font-weight: bold;
      color: #555;
    }

    .stats {
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;
      margin: 20px 0;
    }

    .stat-item {
      text-align: center;
      padding: 15px;
      background: #f8f9fa;
      border-radius: 8px;
      flex: 1;
      margin: 0 10px;
      min-width: 120px;
    }

    .stat-number {
      font-size: 2em;
      font-weight: bold;
      color: #667eea;
    }

    .stat-label {
      color: #666;
    }

    .records-container {
      height: 500px;
      overflow: hidden;
      position: relative;
      margin-top: 20px;
    }

    .records-list {
      animation: scrollAnimation 120s linear infinite;
      animation-fill-mode: none;
      animation-delay: 1s;
      /* 延迟动画开始，确保内容加载完成 */
    }

    .records-list:hover {
      animation-play-state: paused;
    }

    .records-list.paused {
      animation-play-state: paused;
      overflow-y: auto;
      height: 100%;
    }

    @keyframes scrollAnimation {
      0% {
        transform: translateY(0);
      }

      100% {
        transform: translateY(-50%);
      }
    }

    /* 确保克隆的列表也应用动画 */
    #recordsListClone {
      animation: none;
      /* 克隆内容不单独应用动画，跟随父容器滚动 */
    }

    .record-item {
      padding: 15px;
      border-left: 4px solid #667eea;
      background: #f8f9fa;
      margin-bottom: 15px;
      border-radius: 0 5px 5px 0;
      transition: all 0.3s ease;
      cursor: pointer;
    }

    /* .record-item:hover {
      background: #e9ecef;
      transform: translateX(5px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      border-left-color: #5a5a5a;
    } */

    .record-item img {
      margin-right: 10px;
    }

    .record-date {
      font-weight: bold;
      color: #333;
      margin-bottom: 5px;
    }

    .record-pages {
      color: #666;
      margin-bottom: 10px;
      margin-left: 10px;
    }

    .record-notes {
      background: #d2dfff;
      padding: 10px;
      border-radius: 5px;
      border: 1px solid #eee;
      text-indent: 32px;
    }

    /* 朋友圈回复样式 */
    .response-list {
      margin-top: 10px;
      padding: 10px;
      background-color: #f0f0f0;
      border-radius: 5px;
    }

    .response-item {
      display: flex;
      margin-bottom: 8px;
      align-items: flex-start;
    }

    .response-avatar {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      margin-right: 8px;
      flex-shrink: 0;
    }

    .response-content {
      flex: 1;
      background-color: #ffffff;
      padding: 6px 10px;
      border-radius: 12px;
      font-size: 14px;
      line-height: 1.4;
    }

    .response-user {
      font-weight: bold;
      color: #333;
      margin-right: 5px;
    }

    .response-text {
      color: #333;
    }

    /* 回复和点赞链接样式 */
    .reply-link,
    .like-link {
      color: #667eea;
      cursor: pointer;
      margin-top: 10px;
      font-size: 14px;
      display: inline-block;
      margin-right: 15px;
    }

    .reply-link:hover,
    .like-link:hover {
      text-decoration: underline;
    }

    .like-link.liked {
      color: #ff6b6b;
    }

    /* 回复表单样式 */
    .reply-form {
      margin-top: 15px;
      padding: 10px;
      background-color: #f9f9f9;
      border-radius: 5px;
    }

    .reply-form textarea {
      width: 100%;
      height: 60px;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      resize: vertical;
      margin-bottom: 10px;
      box-sizing: border-box;
    }

    .reply-form button {
      background-color: #2196F3;
      color: white;
      border: none;
      padding: 8px 15px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
    }

    .reply-form button:hover {
      background-color: #1976D2;
    }

    footer {
      text-align: center;
      padding: 20px;
      color: #666;
      margin-top: 30px;
    }

    .help-icon {
      position: fixed;
      top: 20px;
      right: 20px;
      width: 40px;
      height: 40px;
      background: #667eea;
      color: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      font-weight: bold;
      font-size: 20px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
      z-index: 1000;
    }

    .modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      z-index: 1001;
      align-items: center;
      justify-content: center;
    }

    .modal-content {
      background: white;
      padding: 30px;
      border-radius: 10px;
      max-width: 600px;
      max-height: 80vh;
      overflow-y: auto;
      position: relative;
    }

    .close {
      position: absolute;
      top: 15px;
      right: 15px;
      font-size: 24px;
      cursor: pointer;
      color: #999;
    }

    @media (max-width: 768px) {
      .container {
        padding: 10px;
      }

      .stat-item {
        margin: 5px;
        min-width: 100px;
      }

      h1 {
        font-size: 1.5em;
      }
    }
  </style>
  <style>
    .tip {
      background-color: #e7f3ff;
      border: 1px solid #b8daff;
      color: #004085;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 10px;
      line-height: 1.6;
      font-size: 16px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    }

    .tip strong {
      color: #0056b3;
      font-weight: bold;
    }

    .card>div>button {
      margin-bottom: 10px;
    }
  </style>
</head>

<body>


  <div class="container">
    <header>
      <button onclick="showDocument()"
        style="display: inline-flex; align-items: center; background-color: #2ecc71; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; font-weight: bold;">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white"
          stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 5px;">
          <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
          <circle cx="12" cy="12" r="3"></circle>
        </svg>
        在线查看
      </button>
      <h1>《华为数字化转型之道》读书打卡小程序</h1>
      <div style="text-align: center; margin: 10px 0;">
        <a href="https://tqi.techlinkpets3d.com/daka/华为数字化转型之道.docx"
          style="display: none; align-items: center; text-decoration: none; color: #3498db; font-weight: bold; margin-right: 20px;"
          target="_blank">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke="#3498db" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 5px;">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
            <polyline points="7 10 12 15 17 10"></polyline>
            <line x1="12" y1="15" x2="12" y2="3"></line>
          </svg>
          点击这里下载
        </a>

      </div>
      <p style="text-align: center;">提升团队对数字化转型的系统认知，推动公司战略落地与组织能力升级</p>

      <div class="user-avatar" id="userAvatar"
        style="position: absolute; top: 15px; right: 50px; width: 40px; height: 40px; border-radius: 50%; display: none;">
        <img id="avatarImg" src="" alt="用户头像" style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;">
      </div>

      <div class="help-icon" onclick="showHelp()">?</div>
    </header>
    <div class="tip">
      <strong>温馨提示：</strong>为统一管理团队对"数字化转型"的认知，学习标杆企业（华为）的系统性方法论。推动公司战略落地与组织能力升级，公司决定在主管级以上人员中开展《华为数字化转型之道》专项读书会。本书系统总结了华为在战略、组织、流程、技术、数据、文化等方面的转型实践，是当前企业数字化转型最具参考价值的实战指南之一。
      <br><br>
      <strong>学习形式：</strong>
      <br>
      <strong><span style="font-size: 24px;">📚</span> 1. 每日阅读钉钉打卡：</strong>使用钉钉工作台"读书打卡"小程序，每日阅读后打卡签到，可分享笔记或心得片段。
      <br>
      <strong><span style="font-size: 24px;">💬</span> 2. 每周群内分享：</strong>每周六在钉钉读书群内展开一次线上分享会，由轮值同事简要分享本章节核心内容及启发。
      <br>
      <strong><span style="font-size: 24px;">✍️</span> 3. 一个月后进行书面总结(即2025年12月13日前，看完书三天内)：</strong>一个月后(12月13日)提交一篇
      800字以上读后感，结合岗位实际，提出改进思路。
    </div>
    <div class="notification">
      <div class="notification-content">
        <strong>📰 读书会通知：</strong> 从11月10日开始,每日阅读11页，共需30天读完329页。请按时打卡并分享读书心得。
      </div>
    </div>

    <!-- 读书活跃度排行榜 -->
    <div class="card">
      <h2 class="card-title">读书活跃度排行榜</h2>
      <div id="hotRank">
        <p style="text-align: center; color: #666;">加载中...</p>
      </div>
    </div>
    <div class="card">
      <h2 class="card-title">今日打卡</h2>
      <form id="dakaForm" method="POST">
        <div class="form-group">
          <label for="readingDate">阅读日期：</label>
          <input type="date" id="readingDate" name="readingDate" required>
        </div>

        <div class="form-group">
          <label for="pagesRead">今日阅读页数：</label>
          <input type="number" id="pagesRead" name="pagesRead" min="1" max="30" value="11" required>
        </div>

        <div class="form-group">
          <label for="notesContainer">读书笔记/心得分享：<span style="color: red;">*</span></label>
          <div style="position: relative; display: inline-block; width: 100%;">
            <div id="notesContainer"
              style="min-height: 120px; padding: 12px; border: 1px solid #ddd; border-radius: 5px; outline: none;"
              contenteditable="true" oninput="updateHiddenNotes()"></div>
            <input type="hidden" id="notes" name="notes" required>
            <!-- 图片上传按钮放在文本框内部右下角 -->
            <button type="button" onclick="triggerRichImageUpload('notesContainer')"
              style="position: absolute; bottom: 8px; right: 8px; width: 36px; height: 36px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: 1px solid rgba(255,255,255,0.3); border-radius: 4px; cursor: pointer; display: flex; align-items: center; justify-content: center; z-index: 10; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"
              title="插入图片">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                <circle cx="8.5" cy="8.5" r="1.5"></circle>
                <polyline points="21 15 16 10 5 21"></polyline>
              </svg>
            </button>
            <input type="file" id="notesImageUpload" accept="image/*" style="display: none;"
              onchange="handleRichImageUpload(this, 'notesContainer')">
          </div>
        </div>

        <button type="submit" class="btn">提交打卡</button>
      </form>
    </div>
    <div class="card">
      <h2 class="card-title">打卡记录 <span style="font-size: 14px; color: #666; font-weight: normal;">(点击区域可暂停自动滚动)</span>
      </h2>
      <div class="records-container">
        <div class="records-list" id="recordsList">
          <!-- 打卡记录将通过JavaScript动态加载 -->
          <p style="text-align: center; color: #666;">暂无打卡记录</p>
        </div>
      </div>
      <div style="text-align: center; margin-top: 20px;">
        <button onclick="showAllRecords()" class="btn">查看全部打卡心得</button>
      </div>
    </div>


    <!-- 个人成绩排行榜 -->
    <div class="card">
      <h2 class="card-title">个人成绩排行榜</h2>
      <div id="leaderboard">
        <p style="text-align: center; color: #666;">加载中...</p>
      </div>
    </div>

    <!-- 末位排行榜 -->
    <div class="card">
      <h2 class="card-title">末位排行榜</h2>
      <div id="bottomLeaderboard">
        <p style="text-align: center; color: #666;">加载中...</p>
      </div>
    </div>





    <div class="card">
      <h2 class="card-title">我的阅读进度</h2>
      <div class="progress-container">
        <div class="progress-bar">
          <div class="progress-fill" id="progressFill" style="width: 0%"></div>
        </div>
        <div class="progress-text" id="progressText">已读 0 页，共 329 页</div>
      </div>

      <div class="stats">
        <div class="stat-item">
          <div class="stat-number" id="daysCompleted">0</div>
          <div class="stat-label">已完成天数</div>
        </div>
        <div class="stat-item">
          <div class="stat-number" id="totalPages">0</div>
          <div class="stat-label">累计阅读页数</div>
        </div>
        <div class="stat-item">
          <div class="stat-number" id="avgPages">0</div>
          <div class="stat-label">日均页数</div>
        </div>
      </div>
    </div>

    <div class="card">
      <div style="margin-top: 10px; display: flex; flex-wrap: wrap; gap: 10px;">
        <button onclick="showActivityNotice('月底书面总结')" class="btn"
          style="flex: 1 1 calc(50% - 5px); min-width: 150px;">月底书面总结</button>
        <button onclick="showActivityNotice('月底线上考试')" class="btn"
          style="flex: 1 1 calc(50% - 5px); min-width: 150px;">月底线上考试</button>
        <button onclick="showStatsModal()" class="btn"
          style="flex: 1 1 calc(50% - 5px); min-width: 150px;">管理统计</button>
        <button onclick="showAllSummarry()" class="btn"
          style="flex: 1 1 calc(50% - 5px); min-width: 150px;">全部书面总结</button>
      </div>



    </div>

    <!-- 帮助说明弹窗 -->
    <div id="helpModal" class="modal">
      <div class="modal-content">
        <span class="close" onclick="closeHelp()">&times;</span>
        <h2>系统使用说明</h2>
        <h3>操作步骤：</h3>
        <ol>
          <li><strong>每日打卡</strong>：每天阅读后，在"今日打卡"区域填写阅读日期、页数和心得，点击"提交打卡"</li>
          <li><strong>查看进度</strong>：在"阅读进度"区域可查看整体阅读进度和统计数据</li>
          <li><strong>查看记录</strong>：在"打卡记录"区域可查看历史打卡记录和分享的笔记</li>
        </ol>

        <h3>读书会安排：</h3>
        <ul>
          <li><strong>每日阅读打卡</strong>：整书共计329页，每天读11页，共需一个月内读完</li>
          <li><strong>每周群内分享</strong>：每周六在钉钉读书群内开展线上分享会</li>
          <li><strong>月底书面总结</strong>：月末提交一篇800字以上读后感</li>
          <li><strong>月底线上考试</strong>：由数字化中心负责组织</li>
        </ul>

        <h3>激励机制：</h3>
        <ul>
          <li><strong>排名奖励</strong>：按分数从高到低排序，奖励前3名（3000元/2000元/1000元）</li>
          <li><strong>末位约束</strong>：倒数后3名需乐捐（800元/600元/300元）</li>
        </ul>
      </div>
    </div>

    <!-- 全部打卡记录弹窗 -->
    <div id="allRecordsModal" class="modal" style="display: none;">
      <div class="modal-content" style="max-width: 900px; width: 95%;">
        <div class="custom-modal-header">
          <span class="close" onclick="closeAllRecords()">&times;</span>
          <h2 style="margin-top: 0;">全部打卡心得记录</h2>
        </div>
        <div style="max-height: 70vh; overflow-y: auto; margin: 20px 0;">
          <table style="width: 100%; border-collapse: collapse;">
            <thead>
              <tr style="background-color: #f8f9fa;">
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center;">记录人</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center;">时间</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center;">内容</th>
              </tr>
            </thead>
            <tbody id="allRecordsTableBody">
              <tr>
                <td colspan="3" style="padding: 40px; text-align: center; color: #666;">正在加载记录...</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <footer>


      <p>© 2025 公司读书会项目 | 《华为数字化转型之道》读书打卡系统</p>

    </footer>

    <!-- 文档查看弹窗 -->
    <div id="documentModal" class="modal">
      <div class="modal-content" style="width: 90%; max-width: 1000px; height: 90vh;">
        <div
          style="display: flex; justify-content: space-between; align-items: center; padding: 15px; border-bottom: 1px solid #eee;">
          <h2 style="margin: 0;">《华为数字化转型之道》</h2>
          <span class="close" onclick="closeDocument()">&times;</span>
        </div>
        <div style="padding: 15px; height: calc(90vh - 100px); overflow: auto;">
          <iframe id="documentFrame" src="" width="100%" height="100%" frameborder="0"></iframe>
        </div>
        <div style="padding: 15px; border-top: 1px solid #eee; text-align: right;">

          <a href="https://tqi.techlinkpets3d.com/daka/华为数字化转型之道.docx"
            style="display: inline-flex; align-items: center; text-decoration: none; color: #3498db; font-weight: bold; margin-right: 15px;">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
              stroke="#3498db" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
              style="margin-right: 5px;">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
              <polyline points="7 10 12 15 17 10"></polyline>
              <line x1="12" y1="15" x2="12" y2="3"></line>
            </svg>
            下载文档
          </a>
          <button onclick="closeDocument()"
            style="background-color: #3498db; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">关闭</button>
        </div>
      </div>
    </div>

    <!-- 自定义弹出层 -->
    <div id="customModal" class="custom-modal">
      <div class="custom-modal-content">
        <div class="custom-modal-header">
          <h3 class="custom-modal-title" id="customModalTitle">提示</h3>
          <span class="custom-modal-close" onclick="closeCustomModal()">&times;</span>
        </div>
        <div class="custom-modal-body">
          <p class="custom-modal-message" id="customModalMessage"></p>
        </div>
        <div class="custom-modal-footer">
          <button class="custom-modal-button" id="customModalButton" onclick="closeCustomModal()">确定</button>
        </div>
      </div>
    </div>

    <!-- 导出数据弹窗 -->
    <div id="exportModal" class="custom-modal" style="z-index: 1010;">
      <div class="custom-modal-content" style="max-width: 500px;">
        <div class="custom-modal-header">
          <h3 class="custom-modal-title">导出功能</h3>
          <span class="custom-modal-close" onclick="closeExportModal()">&times;</span>
        </div>
        <div class="custom-modal-body" style="text-align: center; padding: 30px 20px;">
          <div style="margin-bottom: 20px; font-size: 48px;">📊</div>
          <p style="font-size: 18px; margin-bottom: 15px;">导出功能正在开发中</p>
          <p style="color: #666; font-size: 14px;">我们正在努力开发导出功能，敬请期待！</p>
        </div>
        <div class="custom-modal-footer" style="justify-content: center;">
          <button class="custom-modal-button primary" onclick="closeExportModal()">我知道了</button>
        </div>
      </div>
    </div>

    <!-- 管理统计弹窗 -->
    <div id="statsModal" class="custom-modal">
      <div class="custom-modal-content"
        style="max-width: 90%; width: 1200px; max-height: 80vh; display: flex; flex-direction: column;">
        <div class="custom-modal-header">
          <h3 class="custom-modal-title">管理统计数据</h3>
          <span class="custom-modal-close" onclick="closeStatsModal()">&times;</span>
        </div>
        <div class="custom-modal-body" style="flex: 1; overflow-y: auto; padding: 20px; text-align: left;">
          <table id="statsTable" style="width: 100%; border-collapse: collapse; font-size: 14px;">
            <thead>
              <tr style="background-color: #f8f9fa; position: sticky; top: 0; z-index: 10;">
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">排名</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">姓名</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">阅读数量</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">完成天数</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">已读页数</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">平均阅读页数</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">阅读最新日期</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">得分</th>
              </tr>
            </thead>
            <tbody id="statsTableBody">
              <tr>
                <td colspan="8" style="padding: 20px; text-align: center; color: #666;">加载中...</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="custom-modal-footer">
          <button class="custom-modal-button" onclick="exportStatsData()">导出数据</button>
          <button class="custom-modal-button success" onclick="closeStatsModal()">关闭</button>
        </div>
      </div>
    </div>

    <!-- 全部书面总结弹窗 -->
    <div id="allSummaryModal" class="custom-modal" style="display: none;">
      <div class="custom-modal-content"
        style="max-width: 90%; width: 1200px; max-height: 80vh; display: flex; flex-direction: column;">
        <div class="custom-modal-header">
          <h3 class="custom-modal-title">全部书面总结</h3>
          <span class="custom-modal-close" onclick="closeAllSummary()">&times;</span>
        </div>
        <div class="custom-modal-body" style="flex: 1; overflow-y: auto; padding: 20px; text-align: left;">
          <table id="allSummaryTable" style="width: 100%; border-collapse: collapse; font-size: 14px;">
            <thead>
              <tr style="background-color: #f8f9fa; position: sticky; top: 0; z-index: 10;">
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">序号</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">用户姓名</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">总结日期</th>
                <th style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;">总结内容</th>
              </tr>
            </thead>
            <tbody id="allSummaryTableBody">
              <tr>
                <td colspan="4" style="padding: 40px; text-align: center; color: #666;">正在加载总结记录...</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="custom-modal-footer">
          <button class="custom-modal-button success" onclick="closeAllSummary()">关闭</button>
        </div>
      </div>
    </div>

    <!-- 书面总结弹窗 -->
    <div id="summaryModal" class="custom-modal">
      <div class="custom-modal-content" style="max-width: 600px;">
        <div class="custom-modal-header">
          <h3 class="custom-modal-title">书面总结</h3>
          <span class="custom-modal-close" onclick="closeSummaryModal()">&times;</span>
        </div>
        <div class="custom-modal-body">
          <form id="summaryForm">
            <!-- 添加字数不足提示区域 -->
            <div id="wordCountWarning"
              style="padding: 10px; background-color: #fff3cd; color: #856404; border-radius: 5px; margin-bottom: 15px; display: none;">
              总结内容需要800字以上，请继续完善！
            </div>

            <div class="form-group">
              <label for="summaryDate">阅读日期：</label>
              <input type="date" id="summaryDate" name="summaryDate" required>
            </div>
            <div class="form-group">
              <label for="summaryContainer">总结内容（800字以上）：</label>
              <div style="position: relative; display: inline-block; width: 100%;">
                <div id="summaryContainer"
                  style="min-height: 240px; padding: 12px; border: 1px solid #ddd; border-radius: 5px; outline: none; text-align: left;"
                  contenteditable="true" oninput="updateHiddenSummary()"></div>
                <input type="hidden" id="summaryContent" name="summaryContent" required>
                <!-- 图片上传按钮放在文本框内部右下角 -->
                <button type="button" onclick="triggerRichImageUpload('summaryContainer')"
                  style="position: absolute; bottom: 8px; right: 8px; width: 36px; height: 36px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: 1px solid rgba(255,255,255,0.3); border-radius: 4px; cursor: pointer; display: flex; align-items: center; justify-content: center; z-index: 10; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"
                  title="插入图片">
                  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                    <circle cx="8.5" cy="8.5" r="1.5"></circle>
                    <polyline points="21 15 16 10 5 21"></polyline>
                  </svg>
                </button>
                <input type="file" id="summaryContentImageUpload" accept="image/*" style="display: none;"
                  onchange="handleRichImageUpload(this, 'summaryContainer')">
              </div>
              <div style="text-align: right; margin-top: 5px; font-size: 14px; color: #666;">
                <span id="wordCount">0</span> 字
              </div>
            </div>
          </form>
        </div>
        <div class="custom-modal-footer">
          <button class="custom-modal-button" onclick="closeSummaryModal()">取消</button>
          <button class="custom-modal-button success" id="submitSummaryButton" onclick="submitSummary()">提交</button>
        </div>
      </div>
    </div>

    <script>
      // 富文本编辑相关函数
      function updateHiddenNotes() {
        const notesContainer = document.getElementById('notesContainer');
        document.getElementById('notes').value = notesContainer.innerHTML;
      }

      function updateHiddenSummary() {
        const summaryContainer = document.getElementById('summaryContainer');
        document.getElementById('summaryContent').value = summaryContainer.innerHTML;

        // 更新字数统计
        const text = summaryContainer.textContent || summaryContainer.innerText;
        document.getElementById('wordCount').textContent = text.length;
      }

      function triggerRichImageUpload(containerId) {
        const inputId = containerId === 'notesContainer' ? 'notesImageUpload' : 'summaryContentImageUpload';
        // 先聚焦到对应的文本框
        const container = document.getElementById(containerId);
        if (container) {
          container.focus();
        }
        // 然后触发文件上传
        document.getElementById(inputId).click();
      }

      function handleRichImageUpload(input, containerId) {
        if (input.files && input.files[0]) {
          // 检查文件类型
          const file = input.files[0];
          if (!file.type.match('image.*')) {
            alert('请选择图片文件');
            return;
          }

          // 检查文件大小（限制为5MB）
          const maxSize = 5 * 1024 * 1024; // 5MB
          if (file.size > maxSize) {
            alert('图片大小不能超过5MB');
            return;
          }

          // 创建FileReader读取图片
          const reader = new FileReader();
          reader.onload = function (e) {
            const imageData = e.target.result;
            const container = document.getElementById(containerId);

            // 创建图片元素
            const img = document.createElement('img');
            img.src = imageData;
            // 设置统一的图片大小，最大宽度固定为600px，保持宽高比
            img.style.maxWidth = '600px';
            img.style.width = '100%';
            img.style.height = 'auto';
            img.style.margin = '8px 0';
            img.style.borderRadius = '4px';
            img.style.display = 'block';

            // 将图片插入到当前光标位置
            insertAtCursor(container, img);

            // 添加一个换行，方便后续编辑
            const br = document.createElement('br');
            insertAtCursor(container, br);

            // 更新隐藏字段
            if (containerId === 'notesContainer') {
              updateHiddenNotes();
            } else {
              updateHiddenSummary();
            }
          };

          reader.readAsDataURL(input.files[0]);
          input.value = ''; // 清空input，允许重复选择同一文件
        }
      }

      function insertAtCursor(container, element) {
        const selection = window.getSelection();
        const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;

        if (range) {
          range.deleteContents();
          range.insertNode(element);

          // 将光标移动到插入元素后面
          range.setStartAfter(element);
          range.setEndAfter(element);
          selection.removeAllRanges();
          selection.addRange(range);
        } else {
          // 如果无法获取光标位置，直接追加
          container.appendChild(element);
        }
      }

      // 获取URL参数的函数
      function getUrlParameter(name) {
        name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
        var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
        var results = regex.exec(window.location.href);
        return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
      }

      // 显示自定义弹出层
      function showCustomModal(message, title = "提示", type = "info") {
        const modal = document.getElementById('customModal');
        const titleElement = document.getElementById('customModalTitle');
        const messageElement = document.getElementById('customModalMessage');
        const button = document.getElementById('customModalButton');

        titleElement.textContent = title;
        messageElement.textContent = message;

        // 根据类型设置按钮样式
        button.className = "custom-modal-button";
        if (type === "success") {
          button.classList.add("success");
        } else if (type === "error") {
          button.classList.add("error");
        }

        modal.style.display = "block";
      }

      // 关闭自定义弹出层
      function closeCustomModal() {
        const modal = document.getElementById('customModal');
        modal.style.display = "none";
      }

      // 显示活动未开启提示
      function showActivityNotice(activityName) {
        if (activityName === '月底书面总结') {
          // 显示书面总结弹窗
          showSummaryModal();
        } else if (activityName === '月底线上考试') {
          // 显示月底线上考试功能正在开发中的提示
          showCustomModal('月底线上考试功能正在开发中，敬请期待！', '提示', 'info');
        } else {
          // 对于其他活动，保持原有提示
          showCustomModal('月底考试评分活动还未开启', '提示', 'info');
        }
      }

      // 显示管理统计弹窗
      function showStatsModal() {
        const modal = document.getElementById('statsModal');
        modal.style.display = "block";

        // 加载统计数据
        loadStatsData();
      }

      // 关闭管理统计弹窗
      function closeStatsModal() {
        const modal = document.getElementById('statsModal');
        modal.style.display = "none";
      }

      // 加载统计数据
      function loadStatsData() {
        const tableBody = document.getElementById('statsTableBody');
        // 先清空表格内容，避免缓存问题
        tableBody.innerHTML = '';
        // 显示加载中状态
        tableBody.innerHTML = '<tr><td colspan="8" style="padding: 20px; text-align: center; color: #666;">加载中...</td></tr>';

        // 调用all_rank接口获取数据
        fetch('https://tqi.techlinkpets3d.com/api/daka/all_rank', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          cache: 'no-cache'
        })
          .then(response => response.json())
          .then(data => {
            if (data.code === 1 && data.data && Array.isArray(data.data)) {
              // 按已读页数(totalPages)降序排序，实现排名功能
              // 确保数据正确排序：将totalPages转换为数字类型
              const sortedData = [...data.data].sort((a, b) => {
                // 转换为数字类型，使用Number()确保正确处理各种情况
                const pagesA = Number(a.totalPages) || Number(a.read_count) || 0;
                const pagesB = Number(b.totalPages) || Number(b.read_count) || 0;
                // 降序排序：已读页数多的排在前面
                return pagesB - pagesA;
              });

              // 如果数据为空，显示无数据提示而不是缓冲
              if (sortedData.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="8" style="padding: 20px; text-align: center; color: #666;">暂无统计数据</td></tr>';
              } else {
                renderStatsTable(sortedData);
              }
            } else {
              tableBody.innerHTML = '<tr><td colspan="8" style="padding: 20px; text-align: center; color: #666;">暂无统计数据</td></tr>';
            }
          })
          .catch(error => {
            console.error('获取统计数据失败:', error);
            tableBody.innerHTML = '<tr><td colspan="8" style="padding: 20px; text-align: center; color: #666;">暂无统计数据</td></tr>';
          });
      }

      // 渲染统计表格
      function renderStatsTable(data) {
        const tableBody = document.getElementById('statsTableBody');
        let html = '';

        data.forEach((item, index) => {
          // 使用API返回的实际数据
          const daysCompleted = item.daysCompleted || 0; // 完成天数
          const totalPages = item.totalPages || 0; // 已读页数
          const avgPages = item.avgPages || 0; // 平均阅读页数
          // const readScore = item.read_score || 0; // 阅读分数
          const readScore = 0;

          // 使用data.latest_add_time作为阅读最新日期，添加日期有效性检查
          let lastReadDate = '--：--';
          if (item.latest_add_time) {
            const date = new Date(item.latest_add_time);
            // 检查日期是否有效
            if (!isNaN(date.getTime())) {
              lastReadDate = date.toLocaleDateString('zh-CN');
            }
          }

          html += `
            <tr style="${index % 2 === 0 ? 'background-color: #fff;' : 'background-color: #f8f9fa;'} hover:background-color: #e9ecef;">
              <td style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold; color: ${index < 3 ? (index === 0 ? '#FFD700' : index === 1 ? '#C0C0C0' : '#CD7F32') : '#333'};">${index + 1}</td>
              <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">
                <div style="display: flex; align-items: center; justify-content: center;">
                  <img src="${item.avatar || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'}" alt="${item.nickname}" style="width: 32px; height: 32px; border-radius: 50%; margin-right: 8px;">
                  <span>${item.nickname}</span>
                </div>
              </td>
              <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">
                <div style="margin-bottom: 5px;">${totalPages}</div>
                <div style="width: 100px; margin: 0 auto; height: 8px; background-color: #e0e0e0; border-radius: 4px; overflow: hidden;">
                  <div style="height: 100%; background-color: #4CAF50; width: ${Math.min(100, (totalPages / 329) * 100)}%;"></div>
                </div>
              </td>
              <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">${daysCompleted}天</td>
              <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">${totalPages}页</td>
              <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">${avgPages}页/天</td>
              <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">${lastReadDate}</td>
              <td style="padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold; color: #3f51b5;">${readScore}分</td>
            </tr>
          `;
        });

        tableBody.innerHTML = html;
      }

      // 导出统计数据
      function exportStatsData() {
        showExportModal();
      }

      // 显示导出数据弹窗
      function showExportModal() {
        const modal = document.getElementById('exportModal');
        modal.style.display = "block";
      }

      // 关闭导出数据弹窗
      function closeExportModal() {
        const modal = document.getElementById('exportModal');
        modal.style.display = "none";
      }

      // 显示书面总结弹窗
      function showSummaryModal() {
        const modal = document.getElementById('summaryModal');
        // 设置默认日期为今天
        document.getElementById('summaryDate').valueAsDate = new Date();
        // 重置字数统计
        document.getElementById('wordCount').textContent = '0';
        // 清空文本域
        document.getElementById('summaryContent').value = '';
        // 监听文本域输入事件，更新字数统计
        document.getElementById('summaryContent').oninput = function () {
          document.getElementById('wordCount').textContent = this.value.length;
        };
        modal.style.display = "block";
      }

      // 关闭书面总结弹窗
      function closeSummaryModal() {
        const modal = document.getElementById('summaryModal');
        modal.style.display = "none";
      }

      // 提交书面总结
      function submitSummary() {
        const summaryContainer = document.getElementById('summaryContainer');
        const summaryDate = document.getElementById('summaryDate').value;

        // 确保隐藏字段已更新
        updateHiddenSummary();
        const summaryContent = document.getElementById('summaryContent').value;

        // 隐藏可能存在的提示信息
        const wordCountWarning = document.getElementById('wordCountWarning');
        if (wordCountWarning) {
          wordCountWarning.style.display = 'none';
        }

        // 检查字数是否符合要求（使用纯文本内容计算字数）
        const textContent = summaryContainer.textContent || summaryContainer.innerText;
        if (textContent.length < 800) {
          // 创建或更新字数提示信息
          let wordCountWarning = document.getElementById('wordCountWarning');
          if (!wordCountWarning) {
            wordCountWarning = document.createElement('div');
            wordCountWarning.id = 'wordCountWarning';
            wordCountWarning.style.color = 'red';
            wordCountWarning.style.marginTop = '5px';
            wordCountWarning.style.fontSize = '14px';
            const formGroup = document.querySelector('#summaryModal .form-group');
            if (formGroup) {
              formGroup.appendChild(wordCountWarning);
            }
          }
          wordCountWarning.textContent = '总结内容至少需要800字！';
          wordCountWarning.style.display = 'block';

          // 滚动到顶部以确保用户能看到提示
          const modalBody = document.querySelector('#summaryModal .custom-modal-body');
          if (modalBody) {
            modalBody.scrollTop = 0;
          }
          return;
        }

        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }

        // 创建FormData对象，使用与心得相同的API接口存储
        const formData = new FormData();
        formData.append('uid', uid);
        formData.append('reading_date', summaryDate);
        // 添加标识字段区分是月底总结
        formData.append('is_monthly_summary', '1');
        // 将总结内容作为笔记/心得提交
        formData.append('notes', `【月底书面总结】\n${summaryContent}`);
        // 添加默认阅读页数（月底总结不计入阅读页数统计）
        formData.append('pages_read', '0');

        // 发送数据到服务器，使用心得的API接口
        fetch('https://tqi.techlinkpets3d.com/api/daka/record', {
          method: 'POST',
          body: formData
        })
          .then(response => response.json())
          .then(data => {
            if (data.code == 1) {
              showCustomModal('书面总结提交成功！', '成功', 'success');
              // 关闭总结弹窗
              closeSummaryModal();
              // 更新页面上的记录列表
              updateProgress();
            } else {
              // 增加对message字段的容错处理
              const errorMessage = data.message || data.msg || '未知错误';
              showCustomModal('提交失败：' + errorMessage, '错误', 'error');
            }
          })
          .catch(error => {
            console.error('网络错误:', error);
            showCustomModal('网络错误，请稍后再试', '错误', 'error');
          });
      }

      // 显示全部书面总结弹窗
      function showAllSummarry() {
        const allSummaryModal = document.getElementById('allSummaryModal');
        allSummaryModal.style.display = 'flex';
        // 加载总结数据
        loadAllSummaryData();
      }

      // 关闭全部书面总结弹窗
      function closeAllSummary() {
        const allSummaryModal = document.getElementById('allSummaryModal');
        allSummaryModal.style.display = 'none';
      }

      // 加载全部书面总结数据
      function loadAllSummaryData() {
        const tableBody = document.getElementById('allSummaryTableBody');

        // 清空表格内容并显示加载状态
        tableBody.innerHTML = '<tr><td colspan="4" style="padding: 40px; text-align: center; color: #666;">加载中...</td></tr>';

        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }

        // 从实际API获取所有打卡记录，然后过滤出月底总结
        fetch('https://tqi.techlinkpets3d.com/api/daka/daka_record?uid=' + encodeURIComponent(uid), {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
          })
          .then(data => {
            if (data.code == 1 && data.data && Array.isArray(data.data)) {
              // 过滤出包含"【月底书面总结】"标记的记录
              const summaryData = data.data.filter(record =>
                record.notes && record.notes.includes('【月底书面总结】')
              ).map(record => ({
                id: record.id,
                username: record.username,
                date: record.reading_date || record.add_time,
                // 移除"【月底书面总结】"标记和换行符
                content: record.notes.replace('【月底书面总结】\n', '')
              }));

              // 清空表格内容
              tableBody.innerHTML = '';

              // 检查数据是否为空
              if (summaryData.length === 0) {
                // 显示暂无记录提示
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = `
                  <td colspan="4" style="padding: 40px; text-align: center; color: #666;">暂无月底总结记录</td>
                `;
                tableBody.appendChild(emptyRow);
              } else {
                // 按日期倒序排列（最新的在前）
                summaryData.sort((a, b) => new Date(b.date) - new Date(a.date));

                // 渲染数据
                summaryData.forEach((summary, index) => {
                  const row = document.createElement('tr');
                  // 设置交替行背景色
                  if (index % 2 === 1) {
                    row.style.backgroundColor = '#f8f9fa';
                  }

                  row.innerHTML = `
                    <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">${index + 1}</td>
                    <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">${summary.username}</td>
                    <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">${summary.date}</td>
                    <td style="padding: 12px; border: 1px solid #ddd; text-align: left; white-space: pre-wrap; max-width: 500px;">${summary.content}</td>
                  `;

                  tableBody.appendChild(row);
                });
              }
            }
          })
          .catch(error => {
            console.error('加载月底总结失败:', error);
            tableBody.innerHTML = '<tr><td colspan="4" style="padding: 40px; text-align: center; color: #e74c3c;">加载失败，请稍后重试</td></tr>';
          });
      }

      // 点击弹出层背景关闭弹出层
      window.onclick = function (event) {
        const modal = document.getElementById('customModal');
        const summaryModal = document.getElementById('summaryModal');
        const statsModal = document.getElementById('statsModal');
        const allSummaryModal = document.getElementById('allSummaryModal');

        if (event.target == modal) {
          closeCustomModal();
        }

        if (event.target == summaryModal) {
          closeSummaryModal();
        }

        if (event.target == statsModal) {
          closeStatsModal();
        }

        if (event.target == allSummaryModal) {
          closeAllSummary();
        }
      }

      // 获取uid参数，如果为undefined或空则默认为204
      var uid = getUrlParameter('uid');
      if (uid === undefined || uid === null || uid === '') {
        uid = '204';
      }

      // 设置默认日期为今天
      document.getElementById('readingDate').valueAsDate = new Date();

      // 显示帮助弹窗
      function showHelp() {
        document.getElementById('helpModal').style.display = 'flex';
      }

      // 关闭帮助弹窗
      function closeHelp() {
        document.getElementById('helpModal').style.display = 'none';
      }

      // 显示文档弹窗
      function showDocument() {
        const modal = document.getElementById('documentModal');
        const iframe = document.getElementById('documentFrame');
        // 使用Google Docs Viewer来在线查看文档
        iframe.src = 'https://www.kdocs.cn/l/ccTbpCOprRrx';
        modal.style.display = 'flex';
      }

      // 关闭文档弹窗
      function closeDocument() {
        const modal = document.getElementById('documentModal');
        const iframe = document.getElementById('documentFrame');
        modal.style.display = 'none';
        // 清空iframe内容以提高性能
        iframe.src = '';
      }

      // 点击弹窗外部关闭（帮助弹窗和文档弹窗）
      window.addEventListener('click', function (event) {
        const helpModal = document.getElementById('helpModal');
        const documentModal = document.getElementById('documentModal');
        const customModal = document.getElementById('customModal');
        const summaryModal = document.getElementById('summaryModal');

        if (event.target == helpModal) {
          helpModal.style.display = 'none';
        }

        if (event.target == documentModal) {
          documentModal.style.display = 'none';
          // 清空iframe内容以提高性能
          document.getElementById('documentFrame').src = '';
        }

        if (event.target == customModal) {
          closeCustomModal();
        }

        if (event.target == summaryModal) {
          closeSummaryModal();
        }
      });

      // 从服务器获取数据并更新进度条
      function updateProgress() {
        // 演示数据
        const demoData = {
          success: true,
          data: {
            stats: {
              totalPages: 256,
              totalBookPages: 329,
              daysCompleted: 24,
              avgPages: 10.7
            },
            records: [
              { reading_date: "2025-01-15", pages_read: 11, notes: "今天读了关于数字化转型的第一章，内容很丰富。" },
              { reading_date: "2025-01-14", pages_read: 11, notes: "学习了数字化转型的框架，很有启发。" },
              { reading_date: "2025-01-13", pages_read: 11, notes: "了解了华为数字化转型的历程，受益匪浅。" },
              { reading_date: "2025-01-12", pages_read: 11, notes: "对数字化转型有了更深入的理解。" },
              { reading_date: "2025-01-11", pages_read: 11, notes: "学习了数字化转型的关键要素。" }
            ]
          }
        };

        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }

        // 先获取用户进度数据
        fetch('https://tqi.techlinkpets3d.com/api/daka/userprogress?uid=' + encodeURIComponent(uid), {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        })
          .then(response => response.json())
          .then(data => {
            // 修复API响应处理逻辑，使其与实际的API响应格式匹配
            if (data.code === 1) {
              const userData = data.data;

              // 显示用户头像
              if (userData.avatar) {
                document.getElementById('avatarImg').src = userData.avatar;
                document.getElementById('userAvatar').style.display = 'block';
              }

              // 构造统计数据对象
              const stats = {
                totalPages: userData.read_count || 0, // 使用API返回的已读页数
                totalBookPages: 329, // 总页数固定为329页
                daysCompleted: userData.daysCompleted || 0,
                avgPages: userData.avgPages || 0
              };

              // 根据已读页数和总页数计算进度百分比
              const progressPercent = Math.min(100, (stats.totalPages / stats.totalBookPages) * 100);
              // 更新进度条宽度
              document.getElementById('progressFill').style.width = progressPercent + '%';
              document.getElementById('progressText').textContent = `已读 ${stats.totalPages} 页，共 ${stats.totalBookPages} 页`;

              // 更新统计数字
              document.getElementById('daysCompleted').textContent = stats.daysCompleted;
              document.getElementById('totalPages').textContent = stats.totalPages;
              document.getElementById('avgPages').textContent = stats.avgPages;

              // 获取打卡记录列表
              return fetch('https://tqi.techlinkpets3d.com/api/daka/daka_record?uid=' + encodeURIComponent(uid), {
                method: 'GET',
                headers: {
                  'Content-Type': 'application/json'
                }
              });
            } else {
              console.error('获取数据失败:', data.message || data.msg || '未知错误');
              // 使用演示数据
              updateProgressWithDemoData(demoData);
              // 返回一个rejected promise以跳过后续的then处理
              return Promise.reject(new Error('获取用户进度数据失败'));
            }
          })
          .then(response => response.json())
          .then(data => {
            if (data.code === 1) {
              updateRecordsList(data.data);
              console.log("获取数据成功");
            } else {
              console.error('获取打卡记录失败:', data.message || data.msg || '未知错误');
              updateRecordsList([]);
            }
          })
          .catch(error => {
            console.error('网络错误:', error);
            // 使用演示数据
            updateProgressWithDemoData(demoData);
          });
      }

      // 使用演示数据更新进度
      function updateProgressWithDemoData(demoData) {
        const stats = demoData.data.stats;
        const records = demoData.data.records;

        // 确保使用read_count相关的数据作为阅读页数
        const readCount = stats.totalPages; // 演示数据中使用totalPages作为read_count的模拟值

        // 根据已读页数和总页数计算进度百分比
        const progressPercent = Math.min(100, (readCount / stats.totalBookPages) * 100);
        // 更新进度条宽度
        document.getElementById('progressFill').style.width = progressPercent + '%';
        document.getElementById('progressText').textContent = `已读 ${readCount} 页，共 ${stats.totalBookPages} 页`;

        // 更新统计数字
        document.getElementById('daysCompleted').textContent = stats.daysCompleted;
        document.getElementById('totalPages').textContent = stats.totalPages;
        document.getElementById('avgPages').textContent = stats.avgPages;

        // 更新打卡记录列表
        updateRecordsList(records);
      }

      // 更新打卡记录列表
      // 为图片添加预览功能的辅助函数
      function addImagePreviewEvents() {
        const images = document.querySelectorAll('.record-notes img');
        images.forEach(img => {
          // 设置统一的图片大小，最大宽度固定为400px，保持宽高比
          img.style.maxWidth = '400px';
          img.style.width = '100%';
          img.style.height = 'auto';
          img.style.margin = '8px 0';
          img.style.borderRadius = '4px';
          img.onclick = function () {
            previewImage(this.src);
          };
        });
      }

      // 图片预览功能
      function previewImage(imgSrc) {
        // 创建全屏预览元素
        const preview = document.createElement('div');
        preview.style.cssText = `
          position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); 
          display: flex; align-items: center; justify-content: center; z-index: 9999; cursor: pointer;
        `;
        preview.innerHTML = `<img src="${imgSrc}" style="max-width: 90%; max-height: 90%; object-fit: contain;">`;
        preview.onclick = function () {
          document.body.removeChild(preview);
        };
        document.body.appendChild(preview);
      }

      function updateRecordsList(records) {
        const recordsList = document.getElementById('recordsList');

        if (!records || records.length === 0) {
          recordsList.innerHTML = '<p style="text-align: center; color: #666;">暂无打卡记录</p>';
          return;
        }

        let html = '';
        records.forEach(record => {
          if (record.id == 105)
            console.log("responseList:", record.responseList);
          // 生成回复列表HTML
          let responseHtml = ''; //&& Array.isArray(record.responseList) && record.responseList.length > 0
          if (record.responseList) {
            responseHtml = `
              <div class="response-list">
                ${record.responseList.map(response => `
                  <div class="response-item">
                    <img src="${response.avatar || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(response.username || '匿名用户')}" 
                         alt="${response.username || '匿名用户'}" 
                         class="response-avatar" 
                         onerror="this.src='https://ui-avatars.com/api/?name=' + encodeURIComponent('${response.username || '匿名用户'}');">
                    <div class="response-content">
                      <span class="response-user">${response.username || '匿名用户'}:</span>
                      <span class="response-text">${response.title || '无内容'}</span>
                    </div>
                  </div>
                `).join('')}
              </div>
            `;
          }

          html += `
                <div class="record-item">
                    <div class="record-date" style="display:none"></div>
                    <div class="record-pages"><img src='${record.avatar}' alt='${record.username}' width='30' height='30'>${record.username} ${record.add_time}</div>
                    ${record.notes ? `<div class="record-notes">${record.notes}</div>` : ''}
                    ${responseHtml}
                    <div class="reply-link" style="display:none" onclick="showReplyForm(${record.id})">回复</div>
                    <div class="like-link" style="display:none" onclick="toggleLike(${record.id}, this)">点赞</div>
                </div>
                `;
        });

        recordsList.innerHTML = html;

        // 为记录中的图片添加预览功能
        setTimeout(addImagePreviewEvents, 100);
      }

      // 更新读书活跃度排行榜
      function updateHotRank() {
        const hotRankElement = document.getElementById('hotRank');

        // 后备数据
        const fallbackData = [
          { id: 1, nickname: "张三", read_count: 15, read_score: 150, avatar: "" },
          { id: 2, nickname: "李四", read_count: 12, read_score: 120, avatar: "" },
          { id: 3, nickname: "王五", read_count: 10, read_score: 100, avatar: "" },
          { id: 4, nickname: "赵六", read_count: 9, read_score: 90, avatar: "" },
          { id: 5, nickname: "钱七", read_count: 8, read_score: 80, avatar: "" },
          { id: 6, nickname: "孙八", read_count: 7, read_score: 70, avatar: "" },
          { id: 7, nickname: "周九", read_count: 6, read_score: 60, avatar: "" },
          { id: 8, nickname: "吴十", read_count: 5, read_score: 50, avatar: "" },
          { id: 9, nickname: "郑十一", read_count: 4, read_score: 40, avatar: "" },
          { id: 10, nickname: "王十二", read_count: 3, read_score: 30, avatar: "" }
        ];

        // 从服务器获取活跃度排行榜数据
        var url = 'https://tqi.techlinkpets3d.com/api/daka/hot_rank';
        console.log(url);
        fetch(url, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          // 添加时间戳防止缓存
          cache: 'no-cache'
        })
          .then(response => {
            // 检查响应状态
            console.log('Hot rank API response status:', response.status);
            console.log('Hot rank API response headers:', [...response.headers.entries()]);

            // 检查Content-Type
            const contentType = response.headers.get('content-type');
            console.log('Hot rank API Content-Type:', contentType);

            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 检查Content-Type是否为JSON
            if (contentType && !contentType.includes('application/json')) {
              console.warn('Response Content-Type is not JSON:', contentType);
            }

            return response.text(); // 先获取文本内容
          })
          .then(text => {
            console.log('Hot rank API raw response length:', text.length);
            console.log('Hot rank API raw response (first 500 chars):', text.substring(0, 500));

            // 检查是否为空响应
            if (!text || text.trim() === '') {
              throw new Error('Empty response from server');
            }

            // 检查响应是否包含HTML
            if (text.trim().startsWith('<') || text.includes('<html') || text.includes('<!DOCTYPE')) {
              console.warn('Response appears to be HTML, not JSON');
              throw new Error('Server returned HTML instead of JSON: ' + text.substring(0, 100) + '...');
            }

            // 尝试解析为JSON
            try {
              const data = JSON.parse(text);
              console.log('Hot rank API parsed JSON:', data);

              if (data.code === 1) {
                const hotRankData = data.data.map((item, index) => ({
                  rank: index + 1,
                  name: item.nickname,
                  score: item.read_count || 0,
                  pages: item.read_score || 0,
                  count: item.count || 0,
                  avatar: item.avatar || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
                }));

                renderHotRank(hotRankData, hotRankElement);
              } else {
                // 使用后备数据
                console.warn('API returned error code, using fallback data');
                const hotRankData = fallbackData.map((item, index) => ({
                  rank: index + 1,
                  name: item.nickname,
                  score: item.read_score,
                  pages: item.read_count,
                  count: item.count || 0,
                  avatar: 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
                }));
                renderHotRank(hotRankData, hotRankElement);
              }
            } catch (e) {
              // 使用后备数据
              console.warn('Failed to parse JSON, using fallback data:', e);
              console.warn('Response text that failed to parse:', text);
              const hotRankData = fallbackData.map((item, index) => ({
                rank: index + 1,
                name: item.nickname,
                score: item.read_score,
                pages: item.read_count,
                count: item.count,
                avatar: 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
              }));
              renderHotRank(hotRankData, hotRankElement);
            }
          })
          .catch(error => {
            // 使用后备数据
            console.error('Network error, using fallback data:', error);
            const hotRankData = fallbackData.map((item, index) => ({
              rank: index + 1,
              name: item.nickname,
              score: item.read_score,
              pages: item.read_count,
              count: item.count,
              avatar: 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
            }));
            renderHotRank(hotRankData, hotRankElement);
          });
      }

      // 更新排行榜
      function updateLeaderboard() {
        const leaderboardElement = document.getElementById('leaderboard');

        // 后备数据
        const fallbackData = [
          { id: 1, nickname: "张三", read_count: 15, read_score: 150, avatar: "" },
          { id: 2, nickname: "李四", read_count: 12, read_score: 120, avatar: "" },
          { id: 3, nickname: "王五", read_count: 10, read_score: 100, avatar: "" },
          { id: 4, nickname: "赵六", read_count: 9, read_score: 90, avatar: "" },
          { id: 5, nickname: "钱七", read_count: 8, read_score: 80, avatar: "" },
          { id: 6, nickname: "孙八", read_count: 7, read_score: 70, avatar: "" },
          { id: 7, nickname: "周九", read_count: 6, read_score: 60, avatar: "" },
          { id: 8, nickname: "吴十", read_count: 5, read_score: 50, avatar: "" },
          { id: 9, nickname: "郑十一", read_count: 4, read_score: 40, avatar: "" },
          { id: 10, nickname: "王十二", read_count: 3, read_score: 30, avatar: "" }
        ];

        // 从服务器获取排行榜数据
        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }
        var url = 'https://tqi.techlinkpets3d.com/api/daka/person_rank';
        console.log(url);
        fetch(url, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          // 添加时间戳防止缓存
          cache: 'no-cache'
        })
          .then(response => {
            // 检查响应状态
            console.log('Leaderboard API response status:', response.status);
            console.log('Leaderboard API response headers:', [...response.headers.entries()]);

            // 检查Content-Type
            const contentType = response.headers.get('content-type');
            console.log('Leaderboard API Content-Type:', contentType);

            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 检查Content-Type是否为JSON
            if (contentType && !contentType.includes('application/json')) {
              console.warn('Response Content-Type is not JSON:', contentType);
            }

            return response.text(); // 先获取文本内容
          })
          .then(text => {
            console.log('Leaderboard API raw response length:', text.length);
            console.log('Leaderboard API raw response (first 500 chars):', text.substring(0, 500));

            // 检查是否为空响应
            if (!text || text.trim() === '') {
              throw new Error('Empty response from server');
            }

            // 检查响应是否包含HTML
            if (text.trim().startsWith('<') || text.includes('<html') || text.includes('<!DOCTYPE')) {
              console.warn('Response appears to be HTML, not JSON');
              throw new Error('Server returned HTML instead of JSON: ' + text.substring(0, 100) + '...');
            }

            // 尝试解析为JSON
            try {
              const data = JSON.parse(text);
              console.log('Leaderboard API parsed JSON:', data);

              if (data.code === 1) {
                const leaderboardData = data.data.map((item, index) => ({
                  rank: index + 1,
                  name: item.nickname,
                  score: item.read_score || 0,
                  pages: item.read_count || 0,
                  avatar: item.avatar || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
                }));

                renderLeaderboard(leaderboardData, leaderboardElement);
              } else {
                // 使用后备数据
                console.warn('API returned error code, using fallback data');
                const leaderboardData = fallbackData.map((item, index) => ({
                  rank: index + 1,
                  name: item.nickname,
                  score: item.read_score,
                  pages: item.read_count,
                  avatar: 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
                }));
                renderLeaderboard(leaderboardData, leaderboardElement);
              }
            } catch (e) {
              // 使用后备数据
              console.warn('Failed to parse JSON, using fallback data:', e);
              console.warn('Response text that failed to parse:', text);
              const leaderboardData = fallbackData.map((item, index) => ({
                rank: index + 1,
                name: item.nickname,
                score: item.read_score,
                pages: item.read_count,
                avatar: 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
              }));
              renderLeaderboard(leaderboardData, leaderboardElement);
            }
          })
          .catch(error => {
            // 使用后备数据
            console.error('Network error, using fallback data:', error);
            const leaderboardData = fallbackData.map((item, index) => ({
              rank: index + 1,
              name: item.nickname,
              score: item.read_score,
              pages: item.read_count,
              avatar: 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
            }));
            renderLeaderboard(leaderboardData, leaderboardElement);
          });
      }

      // 渲染读书活跃度排行榜
      function renderHotRank(data, container) {
        if (!data || data.length === 0) {
          container.innerHTML = '<p style="text-align: center; color: #666;">暂无排行榜数据</p>';
          return;
        }

        let html = `
            <div style="display: flex; justify-content: center; flex-wrap: wrap; gap: 10px;">
            `;

        // 显示前10名
        data.slice(0, 10).forEach((person, index) => {
          // 为前三名添加特殊样式
          let rankStyle = "";
          if (index === 0) {
            rankStyle = "color: #FFD700; font-weight: bold;"; // 金色
          } else if (index === 1) {
            rankStyle = "color: #C0C0C0; font-weight: bold;"; // 银色
          } else if (index === 2) {
            rankStyle = "color: #CD7F32; font-weight: bold;"; // 铜色
          }

          html += `
                <div style="text-align: center; padding: 12px; border-radius: 8px; background-color: #f8f9fa; box-shadow: 0 2px 4px rgba(0,0,0,0.1); width: 100px;">
                    <img src="${person.avatar}" alt="${person.name}" onerror="this.src='https://ui-avatars.com/api/?name=${encodeURIComponent(person.name)}&background=random'" style="width: 64px; height: 64px; border-radius: 50%; margin-bottom: 10px;">
                    <div style="font-weight: bold; ${rankStyle}">${person.name}</div>
                    <div style="font-size: 14px; color: #666;">排名: ${person.rank}</div>
                    <div style="font-size: 14px; color: #666;">已读: ${person.pages}页</div>
                    <div style="font-size: 14px; color: #666;">发表: ${person.count}篇</div>
                </div>
                `;
        });

        html += `
            </div>
            `;

        container.innerHTML = html;
      }

      // 渲染排行榜的辅助函数
      function renderLeaderboard(leaderboardData, leaderboardElement) {
        if (!leaderboardData || leaderboardData.length === 0) {
          leaderboardElement.innerHTML = '<p style="text-align: center; color: #666;">暂无排行榜数据</p>';
          return;
        }

        let html = `
            <div style="display: flex; justify-content: center; flex-wrap: wrap; gap: 10px;">
            `;

        // 显示前10名
        leaderboardData.slice(0, 10).forEach((person, index) => {
          // 为前三名添加特殊样式
          let rankStyle = "";
          if (index === 0) {
            rankStyle = "color: #FFD700; font-weight: bold;"; // 金色
          } else if (index === 1) {
            rankStyle = "color: #C0C0C0; font-weight: bold;"; // 银色
          } else if (index === 2) {
            rankStyle = "color: #CD7F32; font-weight: bold;"; // 铜色
          }

          html += `
                <div style="text-align: center; padding: 15px; border-radius: 8px; background-color: #f8f9fa; box-shadow: 0 2px 4px rgba(0,0,0,0.1); width: 100px;">
                    <img src="${person.avatar}" alt="${person.name}" onerror="this.src='https://ui-avatars.com/api/?name=${encodeURIComponent(person.name)}&background=random'" style="width: 64px; height: 64px; border-radius: 50%; margin-bottom: 10px;">
                    <div style="font-weight: bold; ${rankStyle}">${person.name}</div>
                    <div style="font-size: 14px; color: #666;">排名: ${person.rank}</div>
                    <div style="font-size: 14px; color: #666;">得分: ${person.score}</div>
                </div>
                `;
        });

        html += `
            </div>
            `;

        leaderboardElement.innerHTML = html;
      }

      // 更新末位排行榜
      function updateBottomLeaderboard() {
        const bottomLeaderboardElement = document.getElementById('bottomLeaderboard');

        // 后备数据
        const fallbackData = [
          { id: 1, nickname: "张三", read_count: 15, read_score: 150, avatar: "" },
          { id: 2, nickname: "李四", read_count: 12, read_score: 120, avatar: "" },
          { id: 3, nickname: "王五", read_count: 10, read_score: 100, avatar: "" },
          { id: 4, nickname: "赵六", read_count: 9, read_score: 90, avatar: "" },
          { id: 5, nickname: "钱七", read_count: 8, read_score: 80, avatar: "" },
          { id: 6, nickname: "孙八", read_count: 7, read_score: 70, avatar: "" },
          { id: 7, nickname: "周九", read_count: 6, read_score: 60, avatar: "" },
          { id: 8, nickname: "吴十", read_count: 5, read_score: 50, avatar: "" },
          { id: 9, nickname: "郑十一", read_count: 4, read_score: 40, avatar: "" },
          { id: 10, nickname: "王十二", read_count: 3, read_score: 30, avatar: "" }
        ];

        // 从服务器获取排行榜数据
        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }
        var url = 'https://tqi.techlinkpets3d.com/api/daka/fail_rank';
        fetch(url, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          // 添加时间戳防止缓存
          cache: 'no-cache'
        })
          .then(response => {
            // 检查响应状态
            console.log('Bottom leaderboard API response status:', response.status);
            console.log('Bottom leaderboard API response headers:', [...response.headers.entries()]);

            // 检查Content-Type
            const contentType = response.headers.get('content-type');
            console.log('Bottom leaderboard API Content-Type:', contentType);

            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 检查Content-Type是否为JSON
            if (contentType && !contentType.includes('application/json')) {
              console.warn('Response Content-Type is not JSON:', contentType);
            }

            return response.text(); // 先获取文本内容
          })
          .then(text => {
            console.log('Bottom leaderboard API raw response length:', text.length);
            console.log('Bottom leaderboard API raw response (first 500 chars):', text.substring(0, 500));

            // 检查是否为空响应
            if (!text || text.trim() === '') {
              throw new Error('Empty response from server');
            }

            // 检查响应是否包含HTML
            if (text.trim().startsWith('<') || text.includes('<html') || text.includes('<!DOCTYPE')) {
              console.warn('Response appears to be HTML, not JSON');
              throw new Error('Server returned HTML instead of JSON: ' + text.substring(0, 100) + '...');
            }

            // 尝试解析为JSON
            try {
              const data = JSON.parse(text);
              console.log('Bottom leaderboard API parsed JSON:', data);
              console.log('返回是否正确:', data.code);
              if (data.code === 1) {
                // 获取倒数三名的数据
                const allData = data.data.map((item, index) => ({
                  rank: index + 1,
                  name: item.nickname,
                  score: item.read_score || 0,
                  pages: item.read_count || 0,
                  avatar: item.avatar || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
                }));

                renderBottomLeaderboard(allData, bottomLeaderboardElement);
              } else {
                // 使用后备数据
                console.warn('API returned error code, using fallback data');
                const allData = fallbackData.map((item, index) => ({
                  rank: index + 1,
                  name: item.nickname,
                  score: item.read_score,
                  pages: item.read_count,
                  avatar: 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
                }));
                renderBottomLeaderboard(allData, bottomLeaderboardElement);
              }
            } catch (e) {
              // 使用后备数据
              console.warn('Failed to parse JSON, using fallback data:', e);
              console.warn('Response text that failed to parse:', text);
              const allData = fallbackData.map((item, index) => ({
                rank: index + 1,
                name: item.nickname,
                score: item.read_score,
                pages: item.read_count,
                avatar: 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
              }));
              renderBottomLeaderboard(allData, bottomLeaderboardElement);
            }
          })
          .catch(error => {
            // 使用后备数据
            console.error('Network error, using fallback data:', error);
            const allData = fallbackData.map((item, index) => ({
              rank: index + 1,
              name: item.nickname,
              score: item.read_score,
              pages: item.read_count,
              avatar: 'https://ui-avatars.com/api/?name=' + encodeURIComponent(item.nickname) + '&background=random'
            }));
            renderBottomLeaderboard(allData, bottomLeaderboardElement);
          });
      }

      // 渲染末位排行榜的辅助函数
      function renderBottomLeaderboard(allData, bottomLeaderboardElement) {
        // 取最后三名
        const bottomLeaderboardData = allData.slice(-3);

        if (!bottomLeaderboardData || bottomLeaderboardData.length === 0) {
          bottomLeaderboardElement.innerHTML = '<p style="text-align: center; color: #666;">暂无排行榜数据</p>';
          return;
        }

        let html = `
            <div style="display: flex; justify-content: center; flex-wrap: wrap; gap: 15px;">
            `;

        bottomLeaderboardData.forEach((person, index) => {
          // 为末位添加特殊样式
          let rankStyle = "";
          if (person.rank === allData.length - 2) {
            rankStyle = "color: #8B4513; font-weight: bold;"; // 棕色
          } else if (person.rank === allData.length - 1) {
            rankStyle = "color: #A9A9A9; font-weight: bold;"; // 灰色
          } else if (person.rank === allData.length) {
            rankStyle = "color: #8B0000; font-weight: bold;"; // 深红色
          }

          html += `
                <div style="text-align: center; padding: 15px; border-radius: 8px; background-color: #f8f9fa; box-shadow: 0 2px 4px rgba(0,0,0,0.1); width: 100px;">
                    <img src="${person.avatar}" alt="${person.name}" onerror="this.src='https://ui-avatars.com/api/?name=${encodeURIComponent(person.name)}&background=random'" style="width: 64px; height: 64px; border-radius: 50%; margin-bottom: 10px;">
                    <div style="font-weight: bold; ${rankStyle}">${person.name}</div>
                    <div style="font-size: 14px; color: #666;">排名: ${person.rank}</div>
                    <div style="font-size: 14px; color: #666;">得分: ${person.score}</div>
                </div>
                `;
        });

        html += `
            </div>
            `;

        bottomLeaderboardElement.innerHTML = html;
      }

      // 页面加载完成后更新进度和排行榜
      document.addEventListener('DOMContentLoaded', function () {
        updateProgress();
        updateLeaderboard();
        updateBottomLeaderboard();
        updateHotRank(); // 更新读书活跃度排行榜

        // 为轮播添加无缝循环效果
        setTimeout(() => {
          const recordsList = document.getElementById('recordsList');
          if (recordsList) {
            // 确保原始列表有足够内容，如果没有数据则不克隆
            if (recordsList.innerHTML.trim() !== '<p style="text-align: center; color: #666;">暂无打卡记录</p>') {
              const clone = recordsList.cloneNode(true);
              clone.id = 'recordsListClone';
              clone.style.margin = '0'; // 确保克隆内容与原始内容无缝衔接
              recordsList.parentNode.appendChild(clone);
            }

            // 为打卡记录容器添加点击事件，暂停自动滚动并启用手动滚动
            const recordsContainer = document.querySelector('.records-container');
            if (recordsContainer) {
              recordsContainer.addEventListener('click', function () {
                recordsList.classList.toggle('paused');
              });
            }
          }
        }, 1000); // 延迟1秒执行，确保数据已加载
      });

      // 显示全部打卡记录弹窗
      function showAllRecords() {
        const modal = document.getElementById('allRecordsModal');
        modal.style.display = 'flex';

        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }

        // 加载全部打卡记录
        fetch('https://tqi.techlinkpets3d.com/api/daka/daka_record?uid=' + encodeURIComponent(uid), {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        })
          .then(response => response.json())
          .then(data => {
            const tableBody = document.getElementById('allRecordsTableBody');

            if (data.code === 1 && data.data && data.data.length > 0) {
              let html = '';
              // 按时间倒序排序（最新的在前）
              const sortedRecords = data.data.sort((a, b) => {
                const dateA = new Date(a.add_time || 0);
                const dateB = new Date(b.add_time || 0);
                return dateB - dateA;
              });

              sortedRecords.forEach((record, index) => {
                // 格式化日期
                let formattedDate = '--:--';
                if (record.add_time) {
                  const date = new Date(record.add_time);
                  if (!isNaN(date.getTime())) {
                    formattedDate = date.toLocaleString('zh-CN');
                  }
                }

                html += `
                <tr style="${index % 2 === 0 ? 'background-color: #fff;' : 'background-color: #f8f9fa;'} transition: background-color 0.3s;">
                  <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">
                    <div style="display: flex; align-items: center; justify-content: center;">
                      <img src="${record.avatar || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(record.username || '匿名用户')}" 
                           alt="${record.username || '匿名用户'}" 
                           style="width: 32px; height: 32px; border-radius: 50%; margin-right: 8px;">
                      <span>${record.username || '匿名用户'}</span>
                    </div>
                  </td>
                  <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">${formattedDate}</td>
                  <td style="padding: 12px; border: 1px solid #ddd; text-align: left;">${record.notes || '无内容'}</td>
                </tr>
              `;
              });

              tableBody.innerHTML = html;
            } else {
              tableBody.innerHTML = '<tr><td colspan="3" style="padding: 40px; text-align: center; color: #666;">暂无打卡记录</td></tr>';
            }
          })
          .catch(error => {
            console.error('获取全部打卡记录失败:', error);
            const tableBody = document.getElementById('allRecordsTableBody');
            tableBody.innerHTML = '<tr><td colspan="3" style="padding: 40px; text-align: center; color: #666;">获取记录失败，请稍后重试</td></tr>';
          });
      }

      // 关闭全部打卡记录弹窗
      function closeAllRecords() {
        const modal = document.getElementById('allRecordsModal');
        modal.style.display = 'none';
      }

      // 添加点击弹窗外部关闭弹窗的功能
      window.addEventListener('click', function (event) {
        const modal = document.getElementById('allRecordsModal');
        if (modal && event.target === modal) {
          closeAllRecords();
        }
      });

      // 表单提交处理
      document.getElementById('dakaForm').addEventListener('submit', function (e) {
        e.preventDefault();

        // 验证阅读页数不超过30
        const pagesRead = parseInt(document.getElementById('pagesRead').value);
        if (pagesRead > 30) {
          showCustomModal('阅读页数不可超过30页', '提示', 'error');
          return;
        }

        // 验证读书笔记/心得分享是否填写
        const notesContainer = document.getElementById('notesContainer');
        const notesText = notesContainer.textContent || notesContainer.innerText;
        if (!notesText.trim()) {
          showCustomModal('请填写读书笔记/心得分享', '提示', 'error');
          return;
        }

        // 获取表单数据
        const formData = new FormData(this);

        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }

        // 添加uid到表单数据
        formData.append('uid', uid);

        // 发送数据到服务器
        fetch('https://tqi.techlinkpets3d.com/api/daka/record', {
          method: 'POST',
          body: formData
        })
          .then(response => response.json())
          .then(data => {
            if (data.code == 1) {
              showCustomModal('打卡提交成功！', '成功', 'success');
              // 重置表单
              this.reset();
              document.getElementById('readingDate').valueAsDate = new Date();
              // 更新进度和记录
              updateProgress();
            } else {
              // 增加对message字段的容错处理
              const errorMessage = data.message || data.msg || '未知错误';
              showCustomModal('打卡失败：' + errorMessage, '错误', 'error');
            }
          })
          .catch(error => {
            console.error('网络错误:', error);
            showCustomModal('网络错误，请稍后再试', '错误', 'error');
          });
      });

      // 显示回复表单
      function showReplyForm(recordId) {
        // 隐藏所有已存在的回复表单
        const existingForms = document.querySelectorAll('.reply-form');
        existingForms.forEach(form => form.remove());

        // 创建回复表单
        const replyForm = document.createElement('div');
        replyForm.className = 'reply-form';
        replyForm.innerHTML = `
          <textarea placeholder="请输入回复内容..." id="replyContent"></textarea>
          <button onclick="submitReply(${recordId})">发送</button>
        `;

        // 找到对应的记录项并添加回复表单
        const recordItem = event.target.closest('.record-item');
        recordItem.appendChild(replyForm);

        // 聚焦到文本框
        replyForm.querySelector('textarea').focus();

        // 防止页面滚动
        event.preventDefault();
        return false;
      }

      // 提交回复
      function submitReply(recordId) {
        const replyContent = document.getElementById('replyContent').value;

        // 验证回复内容
        if (!replyContent.trim()) {
          showCustomModal('请输入回复内容', '提示', 'error');
          return;
        }

        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }

        // 准备提交数据
        const data = {
          id: recordId,
          uid: uid,
          title: replyContent
        };

        // 发送数据到服务器
        fetch('https://tqi.techlinkpets3d.com/api/daka/daka_response', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        })
          .then(response => response.json())
          .then(data => {
            if (data.code == 1) {
              showCustomModal('回复提交成功！', '成功', 'success');
              // 移除回复表单
              const replyForm = document.querySelector('.reply-form');
              if (replyForm) replyForm.remove();
              // 更新记录列表
              updateProgress();
            } else {
              const errorMessage = data.message || data.msg || '未知错误';
              showCustomModal('回复失败：' + errorMessage, '错误', 'error');
            }
          })
          .catch(error => {
            console.error('网络错误:', error);
            showCustomModal('网络错误，请稍后再试', '错误', 'error');
          });
      }

      // 点赞功能
      function toggleLike(recordId, element) {
        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }

        // 准备提交数据
        const data = {
          id: recordId,
          uid: uid
        };

        // 发送数据到服务器
        fetch('https://tqi.techlinkpets3d.com/api/daka/daka_like', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        })
          .then(response => response.json())
          .then(data => {
            if (data.code == 1) {
              // 切换点赞状态
              element.classList.toggle('liked');
              if (element.classList.contains('liked')) {
                element.textContent = '已点赞';
              } else {
                element.textContent = '点赞';
              }

              // 如果需要，可以在这里更新UI上的点赞数
              // 例如：更新某个元素的文本内容
              // const likeCountElement = element.closest('.record-item').querySelector('.like-count');
              // if (likeCountElement) {
              //   likeCountElement.textContent = data.like_count || 0;
              // }
            } else {
              const errorMessage = data.message || data.msg || '未知错误';
              showCustomModal('点赞失败：' + errorMessage, '错误', 'error');
            }
          })
          .catch(error => {
            console.error('网络错误:', error);
            showCustomModal('网络错误，请稍后再试', '错误', 'error');
          });

        // 防止页面滚动
        event.preventDefault();
        return false;
      }

      // 显示意见反馈表单
      function showFeedbackForm() {
        // 创建反馈表单
        const feedbackForm = document.createElement('div');
        feedbackForm.className = 'custom-modal';
        feedbackForm.id = 'feedbackModal';
        feedbackForm.innerHTML = `
          <div class="custom-modal-content" style="width: 90%; max-width: 500px;">
            <div class="custom-modal-header">
              <h3 class="custom-modal-title">意见反馈</h3>
              <span class="custom-modal-close" onclick="closeFeedbackForm()">&times;</span>
            </div>
            <div class="custom-modal-body" style="padding: 20px;">
              <textarea id="feedbackContent" placeholder="请输入您的宝贵意见和建议..." 
                style="width: 100%; min-height: 150px; padding: 12px; border: 1px solid #ddd; border-radius: 5px; resize: vertical; font-family: 'Microsoft YaHei', Arial, sans-serif;"></textarea>
            </div>
            <div class="custom-modal-footer" style="padding: 15px 20px; text-align: right; border-top: 1px solid #eee;">
              <button class="custom-modal-button" onclick="closeFeedbackForm()">取消</button>
              <button class="custom-modal-button success" onclick="submitFeedback()">提交</button>
            </div>
          </div>
        `;

        // 添加到页面
        document.body.appendChild(feedbackForm);

        // 显示表单
        feedbackForm.style.display = 'block';

        // 聚焦到文本框
        document.getElementById('feedbackContent').focus();
      }

      // 关闭意见反馈表单
      function closeFeedbackForm() {
        const feedbackModal = document.getElementById('feedbackModal');
        if (feedbackModal) {
          feedbackModal.remove();
        }
      }

      // 提交意见反馈
      function submitFeedback() {
        const feedbackContent = document.getElementById('feedbackContent').value;

        // 验证反馈内容
        if (!feedbackContent.trim()) {
          showCustomModal('请输入您的意见和建议', '提示', 'error');
          return;
        }

        // 获取uid参数
        var uid = getUrlParameter('uid');
        if (!uid || uid === '') {
          uid = 204; // 默认uid
        }

        // 准备提交数据
        const data = {
          content: feedbackContent,
          uid: uid
        };

        // 发送数据到服务器
        fetch('https://tqi.techlinkpets3d.com/api/daka/feedback', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        })
          .then(response => response.json())
          .then(data => {
            if (data.code == 1) {
              showCustomModal('感谢您的宝贵意见！', '成功', 'success');
              // 关闭反馈表单
              closeFeedbackForm();
            } else {
              const errorMessage = data.message || data.msg || '未知错误';
              showCustomModal('提交失败：' + errorMessage, '错误', 'error');
            }
          })
          .catch(error => {
            console.error('网络错误:', error);
            showCustomModal('网络错误，请稍后再试', '错误', 'error');
          });
      }

    </script>

    <!-- 意见反馈链接 -->
    <div style="text-align: center; padding: 20px; color: #666; font-size: 14px;">
      <a href="javascript:void(0)" onclick="showFeedbackForm()" style="color: #667eea; text-decoration: none;">提意见</a>
    </div>
</body>

</html>